<?php
namespace Addons\Fission\Controller\H5;

use Models\BaseModel as Model;
use Session;
use Conf;
use Addons\Fission\Helper;
use Addons\QyWechat\Helper as QyHelper;
use Addons\Fission\Services\JsSdk;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Services\WxpayService; 
use Addons\ShopCollection\Controller\Api\SyncPointBigData;
use Addons\WechatOpenPlatform\Services\Wxopenapi;

class Fission extends \BaseController
{
	public function activity_fission(){
		$fid = \Request::get('fid');
		$fission = (new Model('qy_fission'))->find(['id'=>$fid]);
		if(!$fission->id){
			die('活动不存在'); 
		}
		//开启区域限制
		if($fission->isarea){
			if(file_exists(DOXCX_FRAME_PATH . "/Addons/QyWechat/Config/area.php")){
				$area = include_once(DOXCX_FRAME_PATH . "/Addons/QyWechat/Config/area.php");
			}
			$config = (new Model('qy_fission_config'))->find(['wid'=>$fission->wid]);
			// $area = (new Model('qy_area'))->find(['id'=>$fission->area]);
			// $city = (new Model('qy_city'))->find(['city_num'=>$fission->city]);
			// $province = (new Model('qy_province'))->find(['province_num'=>$fission->province]);
			$province = json_decode($area['p'],1)[$fission->province];
			$city = json_decode($area['c'],1)[$fission->province][$fission->city];
			$area = json_decode($area['a'],1)[$fission->city][$fission->area];
			$this->assign("fission", $fission);
			$this->assign("config", $config);
			$this->assign("area", $area);
			$this->assign("city", $city);
			$this->assign("province", $province);
			return $this->show();
		}
		\Redirect::to('activity_fissions.html?fid='.$fid);
	}

    public function activity_fissions(){
		$fid = \Request::get('fid');
		$fission = (new Model('qy_fission'))->find(['id'=>$fid]);
		if(!$fission->id){
			die('活动不存在'); 
		}
		$wid = $fission->wid;
		$jsSdk = JsSdk::getInstance();
		$agency = (new Model('user_agency'))->find(['isadmin' => 1]);
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		if($this->get_user_agent($wid)->domain){
			$redirect_url = urlencode('https://'.$this->get_user_agent($wid)->domain.'/Addons/Fission/H5/Fission/activity_fissions.html?fid='.$fid);
		}else{
			$redirect_url = urlencode(Conf::$http_path_O2O.'/Addons/Fission/H5/Fission/activity_fissions.html?fid='.$fid);
		}
		$auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$qyConfig->corp_id.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
		$code = $_GET['code']??'';
		if($code){			
			// $oauthRes = $jsSdk->oauth2_access_token($gzh->appid,$gzh->appsecret,$code);
			// if($oauthRes['openid']&&$oauthRes['access_token']){
				// $userInfo = $jsSdk->oauth2_user_info($oauthRes['access_token'],$oauthRes['openid']);
				//查询该用户是否添加过企业微信
				$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
				$QyWechatApi = QyWechatApi::getInstance();
				$app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
				$accessToken = $app->access_token;
				$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
				$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
				$resArr = json_decode(curlGet($url),1);

				$users = json_decode($fission->users,1);
				foreach ($users as $user_id) {
					// $qyPet = (new Model('qy_providers_externalcontact_list'))->find(['wid'=>$wid,'external_userid'=>$resArr['external_userid'],'user_id'=>$user_id]);
					// if($qyPet->id){
						$qyEt = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$user_id,'external_userid'=>$resArr['external_userid'],'status'=>0]);
						$fission = (new Model('qy_fission'))->find($fid);
						$qyConfigs = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
						// $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
						$replyConfig = QyHelper::getInstance()->get_message_send_config($wid);
						$apps = QyWechatApi::getInstance()->get_qy_agent_app($qyConfigs->corp_id,$replyConfig->agent_id,$replyConfig->secret);
						$accessTokens = $apps->access_token;
						$tokens = $accessTokens->getToken()['access_token']; // token 数组  token['access_token'] 字符串
						$urls = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$tokens.'&external_userid='.$resArr['external_userid'];
						$resArrs = json_decode(curlGet($urls),1);
						$attention = (new Model("attention"))->find(["appid"=>$fission->authorizer_appid,"UnionID"=>$resArrs["external_contact"]["unionid"],'wid'=>$wid]);
						if(!$attention->id){
							$attention = (new Model("attention"))->find(["appid"=>$fission->authorizer_appid,"UnionID"=>$resArrs["external_contact"]["unionid"]]);
						}
						$user_ids = (new Model("qy_externalcontact_list"))->field("id")->where(["wid"=>$wid,'external_userid'=>$resArr['external_userid']])->list_all_array();
						$res = false;
						foreach ($user_ids as $value){
						    $fu_user = (new Model("qy_fission_user"))->field("bind_uid")->find(["wid"=>$wid,"fid"=>$fission->id,"bind_uid"=>$value["id"]])->get_model_array();
						    if($fu_user["bind_uid"]){
						        $res = true;
						        break;
						    }
						}
						if($fission->type == 1){
							if($qyEt->id){
								if($fission->paohui_link){
									\Redirect::to($fission->paohui_link."/Addons/Fission/H5/Fission/user_poster-{$qyEt->id}-{$fid}.html");
									break;
								}else{
									\Redirect::to("user_poster-{$qyEt->id}-{$fid}.html");
									break;
								}
							}
						}else{
							if($qyEt->id){
								if($fission->paohui_link){
									\Redirect::to($fission->paohui_link."/Addons/Fission/H5/Fission/user_poster-{$qyEt->id}-{$fid}.html");
									break;
								}else if(!$attention->id || !in_array($fission->id, json_decode($attention->EventKey,1))){
									\Redirect::to("code_data-{$fid}.html");
									break;
								}else{
									\Redirect::to("user_poster-{$qyEt->id}-{$fid}.html");
									break;
								}
							}else{
								if($res){
								    \Redirect::to("user_poster-{$fu_user['bind_uid']}-{$fid}.html");
									break;
								}
								\Redirect::to("code_data-{$fid}.html");
								break;
							}
						}
						
					// }	
				}
				$this->assign("fission", $fission);
				return $this->show();
				//$fissionUnionid = (new Model('qy_fission_unionid'))->find(['wid'=>$wid,'unionid'=>$userInfo['unionid']]);
				// $qyPet = (new Model('qy_providers_externalcontact_list'))->find(['wid'=>$wid,'unionid'=>$userInfo['unionid']]);
				// //$bindUser = (new Model('qy_fission_bind_user'))->find(['wid'=>$wid,'ctime'=>$fissionUnionid->ctime]);
				// $qyEt = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'user_id'=>$qyPet->user_id,'createtime'=>$qyPet->createtime]);
				// if($bindUser->id){
				// 	\Redirect::to("user_poster-{$bindUser->id}-{$fid}.html");
				// }
			// }
		}else{
			\Redirect::to($auth_url);
		}
		// $this->assign("auth_url", $auth_url);
		// $this->assign("fission", $fission);
		// return $this->show();
	}

	public function code_data(){
		$fid = \Request::get(1);
		$fission = (new Model('qy_fission'))->find($fid);
		$this->assign("fission", $fission);
		return $this->show();
	}
	
	public function user_poster(){
		$bindUserId = \Request::get(1);
		$fid = \Request::get(2);
		if(!$bindUserId || !$fid){
			die('缺失必要参数');
		}
		// $bindUser = (new Model('qy_fission_bind_user'))->find($bindUserId);
		$bindUser = (new Model('qy_externalcontact_list'))->find($bindUserId);

		$fission = (new Model('qy_fission'))->find($fid);
		$fuser = (new Model('qy_fission_user'))->find(['wid'=>$bindUser->wid,'bind_uid'=>$bindUserId,'fid'=>$fid]);
		if(!$fuser->id){
			$fuser->wid = $bindUser->wid;
			$fuser->bind_uid = $bindUserId;
			$fuser->fid = $fid;
			$fuser->is_new_friend = 0;
			$fuser->status = $bindUser->status;
			$fuser->type = $fission->type;
			// $fuser->ctime = $bindUser->ctime;
			$fuser->ctime = $bindUser->createtime;
			$fuser->save();
		}
		if(!$fuser->qr_code && $fuser->type == 1){
			$wid = $bindUser->wid;
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			$QyWechatApi = QyWechatApi::getInstance();
			$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
			$state = 'fis_user_' . $fuser->id;//企业自定义的state参数，用于区分不同的添加渠道
			$config = [
				 'skip_verify' => $fission->skip_verify?true:false,//外部客户添加时是否无需验证
				 'state' => $state,
				 'user' => QyHelper::get_userid(json_decode($fission->users,1))
			];
			$createRes = $etApp->contact_way->create(2, 2, $config);
			if($createRes['errcode'] == 0){
				$config_id = $createRes['config_id'];
				$getContactWay = $etApp->contact_way->get($config_id)['contact_way'];
				$fuser->state = $state;
				$fuser->config_id = $config_id;
				$fuser->qr_code = $getContactWay['qr_code'];
				$fuser->save();
			}
		}else if($fission->type == 2 && !$fuser->code_image){
			$QyWechatApi = Wxopenapi::get_code($fission->authorizer_appid,"fuser".$fuser->id,$fuser->wid,"QR_LIMIT_STR_SCENE");
			$fuser->code_image = $QyWechatApi;
			$fuser->save();
		}
		
		$this->assign("fuser", $fuser);
		$this->assign("fission", $fission);
		return $this->show();
	}
	
	public function createPoster(){
		$fuserid = \Request::get(1);
		$code = \Request::get(2);
		$fuser = (new Model('qy_fission_user'))->find($fuserid);
		$bind_user = (new Model('qy_externalcontact_list'))->find($fuser->bind_uid);
		$fission = (new Model('qy_fission'))->find($fuser->fid);
		if($code == 3){
			$fission = (new Model('qy_fission'))->find($fuserid);
			$bind_user = (new Model('qy_externalcontact_list'))->find(["external_userid"=>\Request::get(3)]);
		} 
		if($fission->poster_coordinate){
			$coordinate = json_decode($fission->poster_coordinate,1);
			$imgurl_left = $coordinate['imgurl_left'];
			$imgurl_top = $coordinate['imgurl_top'];
		}else{
			$imgurl_left = 162;
			$imgurl_top = 338;
		}

		if($fission->poster_fontstyle){
			$poster_fontstyle = json_decode($fission->poster_fontstyle,1); 
			$color = $poster_fontstyle['color'];
			$size = $poster_fontstyle['size'];
			$left = $poster_fontstyle['left'];
			if(!$left){
				$left = 30;
			}
			$top = $poster_fontstyle['top'];
			if(!$top){
				$top = 3;
			}
		}
		if($fission->avtar_style){
			$avtar_style = json_decode($fission->avtar_style,1);
			
			$avtar_left = $avtar_style['left'];
			$avtar_top = $avtar_style['top'];
		}
		$config = [];
		if(substr($fission->poster_imgurl,0,5) == "https"){
		   $fission->poster_imgurl = 'http'.substr($fission->poster_imgurl,5);
		}
		$config['background'] = [
			'background'=>$fission->poster_imgurl,
			'width'=>800,
			'height'=>1300
		];
		if($code == 3){
			$images = $fission->qr_code;
		}else if($code == 1){
			$images = $fuser->qr_code;
		}else if($code == 2){
			$images = $fuser->code_image;
		}
		$config['image'][0] = [
			'url'=>$images,
			'left'=>$imgurl_left * (590/162),
			'top'=>$imgurl_top * (1090/338),
			'right'=>0,
			'stream'=>0,
			'bottom'=>0,
			'width'=>200,
			'height'=>200,
			'opacity'=>100
		];
		$topa=$avtar_top*(1090/338)-40;
		if($topa<=0){
			$topa=1;
		}
		if($fission->poster_avatar){
			$config['image'][1] = [
				'url'=>'https://'.parse_url($bind_user->avatar)['host'].parse_url($bind_user->avatar)['path'],
				'left'=>$avtar_left*(590/162),
				'top'=>$topa,
				'right'=>0,
				'stream'=>0,
				'bottom'=>0,
				'width'=>100,
				'height'=>100, 
				'opacity'=>100
			];
		}
		if($fission->poster_nickname){
			$config['text'][0] = [
				'text'=>$bind_user->name,
				'left'=>$left*(590/162)+5,
				'top'=>$top*(1090/338)+40,
				'fontPath'=>DOXCX_FRAME_PATH.'pub/fission/font/simhei.ttf',     //字体文件
				'fontSize'=>$size*18,             //字号
				'fontColor'=>implode(',',$this->hex2rgb($color))??'0,0,0',       //字体颜色
				'angle'=>0,
			];
		}
		echo Helper::getInstance()->createPoster($config);
		exit;
	}

	public function help_progres(){
		$fuserid = \Request::get(1);
		$fuser = (new Model('qy_fission_user'))->find($fuserid);
		$fission = (new Model('qy_fission'))->find($fuser->fid);
		$helpUser = (new Model('qy_fission_help_user'))->where(['wid'=>$fuser->wid,'pid'=>$fuser->id,'fid'=>$fuser->fid])->list_all();
		$successCount = (new Model('qy_fission_help_user'))->where(['wid'=>$fuser->wid,'pid'=>$fuser->id,'fid'=>$fuser->fid,'help_status'=>1])->count();
		$sy_number = 0;//下阶段还差人数量
		foreach($helpUser as $k=>$v){
			$bind_user = (new Model('qy_externalcontact_list'))->find($v->help_bind_uid);
			$helpUser[$k]->bind_user = $bind_user;
		}
		//阶段
		$qy_stage_prize = (new Model('qy_stage_prize'))->where(['wid'=>$fuser->wid,'fid'=>$fuser->fid])->list_all_array();
		$stagesort=array_column($qy_stage_prize,'stagesort');
		array_multisort($qy_stage_prize, SORT_ASC, $stagesort);
		$jd =array_column($qy_stage_prize, 'stage_num', 'stagesort');
		ksort($jd);
		$jieduan_name=0;
		$x_jd=0;
		$sum_count=0;
		foreach($qy_stage_prize as $k => $v){
			$sum_count+=$v['stage_num']; 
	  	}
	  	if($successCount>=$sum_count && $successCount>0){
			$x_jd=count($jd);//全部完成
	  	}else{
			foreach($qy_stage_prize as $k => $v){
			  	$jieduan_name+=$v['stage_num']; 
			  	if($successCount >= $jieduan_name && $successCount>0){
				  	continue;
			  	}
			  	if($successCount < $jieduan_name && $successCount>=0){
			  	  	$sy_number = $jieduan_name-$successCount;
				  	$x_jd =  $qy_stage_prize[$k-1]['stagesort'];
				  	break;
			  	}
			}
	  	}
		//奖励类型
	 	$prize_type=[];
		foreach($qy_stage_prize as $k => $v){
			if($v['stagesort']==$x_jd){
				$prize_type=$v;
			break;
			}
	 	}
		$this->assign("x_jd", $x_jd);
		$this->assign("sy_number", $sy_number);
		$this->assign("type", $prize_type['prize_type']);
		switch($prize_type['prize_type']){
			case 1; //二维码
			$this->assign("qrcode", $prize_type['erwei_code']);
		break;
			case 2; //表单链接
			$this->assign("qrcode", $prize_type['form_url']);
		break;
			case 3; //兑换码
			$code_deltal = (new Model("qy_d_code_deltal"))->find(["wid"=>$fuser->wid,"stage_id"=>$prize_type["id"],"finishuserid"=>$fuser->bind_uid,"d_id"=>$prize_type['d_code_id'],"fid"=>$fission->id]);
			if(!$code_deltal->id){
				$newcode = (new Model('qy_d_code_deltal'))->find(['wid'=>$fuser->wid,'status'=>0,'d_id'=>$prize_type['d_code_id']]);
				if($newcode->id){
					$newcode->stage_id = $prize_type['id'];
					$newcode->finishuserid = $fuser->bind_uid;
					$newcode->fid = $fission->id;
					$newcode->dtime = time();
					$newcode->save();
				}
				$code_deltal = $newcode;
			}
		break;
			case 4; //核销码
			$hxcodes=(new Model('qy_hxcode'))->find(['wid'=>$fuser->wid,'finishuserid'=>$fuser->bind_uid,'stage_id'=>$prize_type['id'],"fid"=>$fission->id]);
			if(!$hxcodes->id){
				$hxcode=new Model('qy_hxcode');
				$randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
				$rand = substr($randStr,0,8).$fuser->bind_uid;
				$hxcode->hxcode = $rand;
				$hxcode->finishuserid = $fuser->bind_uid;//客户id
				$hxcode->status = 0;
				$hxcode->stage_id = $prize_type['id']; //领奖
				$hxcode->fid = $fission->id;
				$hxcode->wid = $fission->wid;
				$hxcode->ctime = time();
				$hxcode->save();
				$hxcodes = $hxcode;
			}
		break;
			case 5; 
			$hxcode=new Model('qy_fissred');
			$y_scucess=$hxcode->find(['wid'=>$fuser->wid,'finishuserid'=>$fuser->bind_uid,'stage_id'=>$prize_type['id'],"fid"=>$fission->id]);
			if(!$y_scucess->id){
			  	$hxcode->wid = $fuser->wid;
			  	$hxcode->finishuserid = $fuser->bind_uid;
				$hxcode->hred=$prize_type['redbag'];
			  	$hxcode->fid = $fuser->fid;
			  	$hxcode->status = 0;
			  	$hxcode->stage_id = $prize_type['id'];
			  	$hxcode->hred = $prize_type['redbag'];
			  	$hxcode->ctime = time();
			  	$y_scucess = $hxcode->save();
				$red_url=Helper::getInstance()->get_http_server_name().'/Addons/Fission/H5/Fission/fissred.html?id='.$y_scucess->id;
			}
		break;
		}
	  	//$x_jd 当前完成阶段
	  	//$x_jd < $page 判断当前阶段是否属于已完成阶段 判断客户是否有违规操作
	  	$page = \Request::get("page");
		if($x_jd < $page){
			echo "<script>alert('您未完成任务或已领取过奖励，请手动关闭页面');</script>";;die;
		}
		if(!$page){
			$page = 1;
			if($x_jd){
				$page = $x_jd;
			}
		}
		$qy_stage_prizes = (new Model('qy_stage_prize'))->find(['wid'=>$fuser->wid,'fid'=>$fuser->fid,"stagesort"=>$page])->get_model_array();
		if($qy_stage_prizes["prize_type"] == 1){
			$qy_stage_prizes["qrcode"] = $qy_stage_prizes["erwei_code"];
		}else if($qy_stage_prizes["prize_type"] == 2){
			$qy_stage_prizes["qrcode"] = $qy_stage_prizes["form_url"];
		}else if($qy_stage_prizes["prize_type"] == 3){
			$codes = (new Model("qy_d_code_deltal"))->find(["wid"=>$qy_stage_prizes["wid"],"stage_id"=>$qy_stage_prizes["id"],"finishuserid"=>$fuser->bind_uid,"d_id"=>$qy_stage_prizes['d_code_id'],"fid"=>$qy_stage_prizes["fid"]]);
			$count = (new Model("qy_d_code_deltal"))->where(["wid"=>$qy_stage_prizes["wid"],"status"=>1,"stage_id"=>$qy_stage_prizes["id"],"fid"=>$qy_stage_prizes["fid"]])->count();
			$qy_stage_prizes["qrcode"] = $codes->dcode;
			if($codes->status != 1){
				if($qy_stage_prizes["stagesort"] == 1 && $fission->marked_controls == 1){
					if($qy_stage_prizes["s_num"] - $count <= $fission->marked_control){
						$qy_stage_prizes["marked"] = $fission->markeds;
					}else if($count > $qy_stage_prizes["s_num"]){
						$qy_stage_prizes["marked"] = $fission->marked;
					}else{
						$codes->status = 1;
						$codes->save();
					}
				}else if($count > $qy_stage_prizes["s_num"]){
					$qy_stage_prizes["marked"] = $fission->marked;
				}else{
					$codes->status = 1;
					$codes->save();
				}
			}
		}else if($qy_stage_prizes["prize_type"] == 4){
			$hxcodes = (new Model('qy_hxcode'))->find(['wid'=>$qy_stage_prizes["wid"],'finishuserid'=>$fuser->bind_uid,'stage_id'=>$qy_stage_prizes['id'],"fid"=>$qy_stage_prizes["fid"]]);
			$count = (new Model("qy_hxcode"))->where(["wid"=>$qy_stage_prizes["wid"],"status"=>1,"stage_id"=>$qy_stage_prizes["id"],"fid"=>$qy_stage_prizes["fid"]])->count();
			$severname = Helper::getInstance()->get_http_server_name().'/Addons/Fission/H5/Fission/hxcode.html?';
			\QRcode::png($severname."hxcode={$hxcodes->hxcode}",false,"L",4);
			$img = ob_get_contents();//获取缓冲区内容
			ob_end_clean();//清除缓冲区内容
			$imgInfo = 'data:png;base64,' . chunk_split(base64_encode($img));
			ob_flush();
			$qy_stage_prizes["qrcode"] = $imgInfo;
			if($hxcodes->status != 1){
				if($qy_stage_prizes["stagesort"] == 1 && $fission->marked_controls == 1){
					if($qy_stage_prizes["s_num"] - $count <= $fission->marked_control){
						$qy_stage_prizes["marked"] = $fission->markeds;
					}else if($count > $qy_stage_prizes["s_num"]){
						$qy_stage_prizes["marked"] = $fission->marked;
					}
				}else if($count > $qy_stage_prizes["s_num"]){
					$qy_stage_prizes["marked"] = $fission->marked;
				}
			} 
			
		}else if($qy_stage_prizes["prize_type"] == 5){
			$y_scucess = (new Model('qy_fissred'))->find(['wid'=>$qy_stage_prizes["wid"],'finishuserid'=>$fuser->bind_uid,'stage_id'=>$qy_stage_prizes['id'],"fid"=>$qy_stage_prizes["fid"]]);
			$red_url=Helper::getInstance()->get_http_server_name().'/Addons/Fission/H5/Fission/fissred.html?id='.$y_scucess->id;
			$count = (new	Model("qy_fissred"))->where(["wid"=>$qy_stage_prizes["wid"],"status"=>1,"stage_id"=>$qy_stage_prizes["id"],"fid"=>$qy_stage_prizes["fid"]])->count();
			$qy_stage_prizes["qrcode"] = $red_url;
			if($y_scucess->status != 1){
				if($qy_stage_prizes["stagesort"] == 1 && $fission->marked_controls == 1){
					if($qy_stage_prizes["s_num"] - $count <= $fission->marked_control){
						$qy_stage_prizes["marked"] = $fission->markeds;
					}else if($count > $qy_stage_prizes["s_num"]){
						$qy_stage_prizes["marked"] = $fission->marked;
					}
				}else if($count > $qy_stage_prizes["s_num"]){
					$qy_stage_prizes["marked"] = $fission->marked;
				}
			}
		} else if($qy_stage_prizes["prize_type"] == 6){
			$ets = (new Model("qy_externalcontact_list"))->find($fuser->bind_uid);
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$fuser->wid]);
			$replyConfig = (new Model('qy_message_send_config'))->find(['wid'=>$fuser->wid]);
			$app = QyWechatApi::getInstance()->get_qy_agent_app($qyConfig->corp_id,$replyConfig->agent_id,$replyConfig->secret);
			$accessToken = $app->access_token;
			$token = $accessToken->getToken()['access_token']; 
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$token.'&external_userid='.$ets->external_userid;
			$resArr = json_decode(curlGet($url),1);
			$arr["unionid"] = $resArr["external_contact"]["unionid"];
			$arr["nickname"] = $resArr["external_contact"]["name"];
			$arr["openid"] = $_GET["openid"];
			$arr["sex"] = $ets->gender;
			$this->assign("arr", $arr);
			$this->assign("id", $qy_stage_prizes["id"]);
		}
		$this->assign("fuserid", $fuserid);
		$this->assign("count", count($qy_stage_prize));
		$this->assign("qy_stage_prizes", $qy_stage_prizes);
		$this->assign("helpUser", $helpUser);
		$this->assign("page", $page);
		$this->assign("successCount", $successCount);
		$this->assign("fission", $fission);
		$this->assign("fuser", $fuser);
		return $this->show("H5/Fission/help_progress");
	}

	//点大发放优惠券
	public function setpointbig(){
		setApi();
		$id = $_POST["id"];
		if(!$_POST || !$id){
			return false;
		}
		$qy_stage_prizes = (new Model('qy_stage_prize'))->find($id);
		$wid= $qy_stage_prizes->wid;
		$sc_point_set = (new Model('sc_point_set'))->find(['wid'=>$wid]);
		//发放优惠券
		$pbMemberId = (new SyncPointBigData())->matchCustomer($sc_point_set->da_id,$_POST['unionid']);
  		if(!$pbMemberId){
  			$params = [
  				'aid' => $sc_point_set->da_id,
  				'unionid' => $_POST['unionid'],
  				'mpopenid' => $_POST['openId'],
  				'sex' => $_POST['sex'],
  				'nickname' => $_POST['nickname'],
  				'headimg' => $_POST['headimgurl'],
  				'areafenhong_province' => $_POST['province'],
  				'areafenhong_city' => $_POST['city'],
  			];
  			$pbRegisterMember = (new SyncPointBigData())->registerCustomer($params);
  			$pbMemberId = $pbRegisterMember['id'];
  		}
		if($pbMemberId  && $qy_stage_prizes->pb_coupon_id){
	  		
	  		$sendCoupon = (new SyncPointBigData())->sendCoupon($sc_point_set->da_id,$pbMemberId,$qy_stage_prizes->pb_coupon_id);
	  		\Log::error("渠道活码发放优惠卷: ".json_encode($sendCoupon,320));

	  	}
	  	//设置等级
	  	if($pbMemberId  && $qy_stage_prizes->pb_setlevel_id){
	  		$setLevel = (new SyncPointBigData())->setLevel($sc_point_set->da_id,$pbMemberId,$qy_stage_prizes->pb_setlevel_id);
	  		\Log::error("渠道活码设置等级: ".json_encode($setLevel,320));
	  	}
	  	sendSuccess("领取成功");
	}
	
	public function help_progress(){
		$fuserid = \Request::get(1);
		$type = \Request::get(2); 
		$fuser = (new Model('qy_fission_user'))->find($fuserid);
		$fission = (new Model('qy_fission'))->find($fuser->fid);
		$page = \Request::get("page");
		if($fission->isarea && !$type){
			if(file_exists(DOXCX_FRAME_PATH . "/Addons/QyWechat/Config/area.php")){
				$area = include_once(DOXCX_FRAME_PATH . "/Addons/QyWechat/Config/area.php");
			}
			$config = (new Model('qy_fission_config'))->find(['wid'=>$fission->wid]);
			$province = json_decode($area['p'],1)[$fission->province];
			$city = json_decode($area['c'],1)[$fission->province][$fission->city];
			$area = json_decode($area['a'],1)[$fission->city][$fission->area];
			$this->assign("fission", $fission);
			$this->assign("config", $config);
			$this->assign("area", $area);
			$this->assign("city", $city);
			$this->assign("type", "1");
			$this->assign("fuserid", $fuserid);
			$this->assign("province", $province);
			$this->assign("page", $page);
			return $this->show("H5/Fission/activity_fission");
		}
	    $qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$fuser->wid]);
		if($this->get_user_agent($wid)->domain){
			$redirect_url = urlencode('https://'.$this->get_user_agent($fuser->wid)->domain.'/Addons/Fission/H5/Fission/help_progress-'.$fuserid.'-'.$type.'.html?page='.$page);
		}else{
			$redirect_url = urlencode(Conf::$http_path_O2O.'/Addons/Fission/H5/Fission/help_progress-'.$fuserid.'-'.$type.'.html?page='.$page);
		}
		$auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$qyConfig->corp_id.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
		$code = $_GET['code']??'';
		if($code){
            $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$fuser->wid]);
			$QyWechatApi = QyWechatApi::getInstance();
			$app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
			$accessToken = $app->access_token;
			$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
			$resArr = json_decode(curlGet($url),1);
			$ets = (new Model("qy_externalcontact_list"))->find($fuser->bind_uid);
			if($ets->external_userid != $resArr["external_userid"]){
			    echo "<script>alert('您未完成任务或已领取过奖励，请手动关闭页面。');</script>";;die;
			}
			$openid = $resArr["OpenId"];
			if($fission->paohui_link){
	        	\Redirect::to($fission->paohui_link."/Addons/Fission/H5/Fission/help_progres-{$fuserid}.html?page=".$page."&openid=".$openid);
	      	}else{
	        	\Redirect::to("help_progres-{$fuserid}.html?page=".$page."&openid=".$openid);
	      	}
		}else{
			\Redirect::to($auth_url);
		}
		
	}

	public function fissred(){
		$hxcode=new Model('qy_fissred');
		$id = \Request::get("id")?:\Request::get(1);
		$y_scucess=$hxcode->find(['id'=>$id]);
		if($y_scucess->status){
			echo "<p style='font-size:5em;margin-top: 3em;text-align: center;'>已领取<p>";die;
		}
		$appids = (new Model('qy_wechat_config'))->find(["wid"=>$y_scucess->wid]);
		if($this->get_user_agent($y_scucess->wid)->domain){
			$baseurl = urlencode('https://'.$this->get_user_agent($y_scucess->wid)->domain.'/Addons/Fission/H5/Fission/fissred-'.$y_scucess->id.'.html');
		}else{
			$baseurl = urlencode(Conf::$http_path_O2O.'/Addons/Fission/H5/Fission/fissred-'.$y_scucess->id.'.html');
		}
        $auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appids->corp_id.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
		$CODE = $_GET['code'];
		if(!$CODE){
		    \Redirect::to($auth_url);
		}
		$confing = (new Model('qy_envelopes_confing'))->find(['wid'=>$y_scucess->wid,"type"=>1]);
        if(!$confing->id || $confing->status == 2){
            $pubs = (new Model('pubs'))->find($y_scucess->wid);
            $users = (new Model('user'))->find($pubs->uid);
            if($users->balance < $y_scucess->hred){
                echo '<p style="font-size:5em;margin-top: 3em;text-align: center;">余额不足,请联系管理员充值<p>';die;
            }
            $confing = (new Model('qy_envelopes_confing'))->find(["wid"=>$users->agid]);
        } 
		$wid = $y_scucess->wid;
		$mchid = $confing->mchid; 
		$appid = $appids->corp_id;
		$appKey = $confing->appKey; 
		$apiKey = $confing->apiKey;
		$wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey, $y_scucess->wid);
		$sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$y_scucess->wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$app = $QyWechatApi->get_qy_agent_app($appids->corp_id,$sendConfig->agent_id,$sendConfig->secret);
		$accessToken = $app->access_token;
		$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$CODE;
		$resArr = json_decode(curlGet($url),1);
		$openId =$resArr['OpenId'];
		// dump($resArr);die;
		if (!$openId) exit('获取openid失败');
		$length = 20;
		$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$len = strlen($str)-1;
		$randstr = '';
		for ($i=0;$i<$length;$i++) {
		  $num=mt_rand(0,$len);
		  $randstr .= $str[$num];
		 }
		$outTradeNo = $randstr.$y_scucess->finishuserid; //订单号
		$payAmount = $y_scucess->hred;  //转账金额，单位:元。转账最小金额为0.3元
		$trueName ='';  //收款人真实姓名
		$result = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $trueName);
		if($result==true){
		    if($confing->type != 1){
                $record = new Model("user_recharge_record");
                $record->user_id = $users->id;
                $record->openid = $users->id;
                $record->money = $payAmount;
                $record->recharge_time = time();
                $record->out_trade_no = $outTradeNo;
                $record->transaction_id = $outTradeNo;
                $record->type = 2;
                $record->status = 2;
                $record->save();
                // $users->balance = $users->balance - $payAmount;
                // $users->save();
            }
			$y_scucess->status=1;
			$y_scucess->hxtime=time();
			$y_scucess->save();

		}
		echo '<p style="font-size:5em;margin-top: 3em;text-align: center;">领取成功<p>';
	}
	
	public function hxcode(){
		$hxcode=$_GET['hxcode'];
		// dump($_GET);
		$hxcode_data=(new Model('qy_hxcode'))->find(['hxcode'=>$hxcode]);
		if(!$hxcode_data->id){
			die('数据库操作失败');
		}
		if($hxcode_data->status==1){
			die('<p style="font-size:5em;margin-top: 3em;text-align: center;">已核销过<p>');	
		}else{
			//判断来人是谁	
			// dump(11111);
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$hxcode_data->wid]);
		// dump($qyConfig);die;
		$QyWechatApi = QyWechatApi::getInstance();
		$etApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->externalcontact_secret);
		$wid = $hxcode_data->wid;
		$corp_id=$qyConfig->corp_id;
		Session::set('wid',$qyConfig->wid);
		// $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid,'agent_id'=>$agent_id]);
		$config = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
		$agent_id=$config->agent_id;
		if($_GET['code']){
			$code = $_GET['code'];
			// dump(333333);
			$app = QyWechatApi::getInstance()->get_qy_agent_app($corp_id,$config->agent_id,$config->secret);
			$accessToken = $app->access_token;
			$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
			// $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
			$resArr = json_decode(curlGet($url),1);
			Session::set('UserId',$resArr['UserId']);
			// dump($resArr);
			$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$resArr['UserId']]);
			if(!$qyUser->id){
				// die('无权限');
				echo "<script>alert('无权限');</script>";
					die('无权限');
			}else{
				// dump(2222);
				// $hxcode_data->fid
				// $fission = (new Model('qy_fission'))->find($hxcode_data->fid);
				$fission=(new Model('qy_stage_prize'))->find(['wid'=>$hxcode_data->wid,'fid'=>$hxcode_data->fid,'id'=>$hxcode_data->stage_id]);
				$fissions =	(new Model('qy_fission'))->find($fission->fid);
				
				$hxusers=json_decode($fissions->hxusers);
				if(in_array($qyUser->id,$hxusers)){
					$hxcode_data->status=1;
					$hxcode_data->hxtime=time();
					$hxcode_data->save();
					// die('操作成功');
					echo "<script>alert('操作成功');</script>";
					die('操作成功');
				}else{
					echo "<script>alert('非核销人员');</script>";
					die('非核销人员');
				}
			}
		} else {
			/**if(Helper::getInstance()->get_http_server_name() != Conf::$http_path_O2O){
				$redirect_http_host = Conf::$http_path_O2O;
			}else{
				$redirect_http_host = Helper::getInstance()->get_http_server_name();
			}*/
			if($this->get_user_agent($wid)->domain){
				$redirect_http_host = 'https://'.$this->get_user_agent($wid)->domain;
			}else{
				$redirect_http_host = Conf::$http_path_O2O;
			}
			$redirect_uri = urlencode($redirect_http_host.'/Addons/Fission/H5/Fission/hxcode.html?corp_id='.$corp_id.'&hxcode='.$hxcode.'&agent_id='.$agent_id);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			\Redirect::to("{$url}");
		}

			
		}
		
	}
	
	public function receive_prize(){
		$fid = \Request::get(1);
		$fission = (new Model('qy_fission'))->find($fid);
		/**$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$fission->wid]);
		$QyWechatApi = QyWechatApi::getInstance();
		$userApp = $QyWechatApi->get_qy_app($qyConfig->corp_id,$qyConfig->user_secret);
		$users = json_decode($fission->lj_lxr,1);
		$i = mt_rand(0, count($users)-1);
		$userInfo = $userApp->user->get($users[$i]);
		$this->assign("userInfo", $userInfo);*/
		$this->assign("fission", $fission);
		return $this->show();
	}
	
	public function ranking(){
		$fuserid = \Request::get(1);
		$fuser = (new Model('qy_fission_user'))->find($fuserid);
		$buser = (new Model('qy_externalcontact_list'))->find($fuser->bind_uid);
		$helpUser = (new Model('qy_fission_help_user'))->where(['wid'=>$fuser->wid,'pid'=>$fuser->id,'fid'=>$fuser->fid,'help_status'=>1])->list_all_array();
		$allUser = (new Model('qy_fission_user'))->where(['wid'=>$fuser->wid,'fid'=>$fuser->fid])->list_all_array();
		$sort_arr = [];
		foreach($allUser as $k=>$v){
			$allUser[$k]['bind_user'] = (new Model('qy_externalcontact_list'))->find($v['bind_uid'])->get_model_array();
			$shelpCount = (new Model('qy_fission_help_user'))->where(['wid'=>$v['wid'],'pid'=>$v['id'],'fid'=>$v['fid'],'help_status'=>1])->count();
			$allUser[$k]['helpCount'] = $shelpCount;
			$sort_arr[] = $shelpCount;
		}
		array_multisort($sort_arr, SORT_DESC, $allUser);
		$this->assign("buser", $buser);
		$this->assign("helpUser", $helpUser);
		$this->assign("allUser", $allUser);
		return $this->show();
	}
	/**
     * RGB转 十六进制
     * @param $rgb RGB颜色的字符串 如：rgb(255,255,255);
     * @return string 十六进制颜色值 如：#FFFFFF
     */
    function RGBToHex($rgb){
        $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
        $re = preg_match($regexp, $rgb, $match);
        $re = array_shift($match);
        $hexColor = "#";
        $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
        for ($i = 0; $i < 3; $i++) {
            $r = null;
            $c = $match[$i];
            $hexAr = array();
            while ($c > 16) {
                $r = $c % 16;
                $c = ($c / 16) >> 0;
                array_push($hexAr, $hex[$r]);
            }
            array_push($hexAr, $hex[$c]);
            $ret = array_reverse($hexAr);
            $item = implode('', $ret);
            $item = str_pad($item, 2, '0', STR_PAD_LEFT);
            $hexColor .= $item;
        }
        return $hexColor;
    }
    /**
     * 十六进制 转 RGB
     */
    function hex2rgb($hexColor) {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }

    function get_user_agent($wid){
	    $pubs = (new Model('pubs'))->find($wid);
	    $user = (new Model('user'))->find(['id' => $pubs->uid]);
	    if ($user->agid) {
	        $agent = (new Model('user_agency'))->find(['id' => $user->agid]);
	    } else {
	        $agent = (new Model('user_agency'))->find(['isadmin' => 1]);
	    }
	    return $agent;
	}
	
}